package logic

import (
	"context"
	"errors"
	"math/rand"
	"newuser/modles/cache"
	"newuser/pkg"
	"strconv"
	"time"

	"newuser/userrpc/internal/svc"
	"newuser/userrpc/userrpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type SendSmsLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewSendSmsLogic(ctx context.Context, svcCtx *svc.ServiceContext) *SendSmsLogic {
	return &SendSmsLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// 短信验证码
func (l *SendSmsLogic) SendSms(in *userrpc.SendSmsRequest) (*userrpc.SendSmsResponse, error) {
	// todo: add your logic here and delete this line
	i, err := cache.Rdb.Get(l.ctx, "sendSms"+in.Phone).Int()
	if i >= 1 {
		return nil, errors.New("短信验证码一分钟只能发送一次")
	}
	code := rand.Intn(9000) + 1000
	sms, err := pkg.SendSms(in.Phone, strconv.Itoa(code))
	if err != nil {
		return nil, err
	}
	if sms.Code != 2 {
		return nil, errors.New(sms.Msg)
	}
	cache.Rdb.Incr(l.ctx, "sendSms"+in.Phone)

	cache.Rdb.Set(l.ctx, "sendSms"+in.Phone, code, time.Minute*3)

	return &userrpc.SendSmsResponse{}, nil
}
